from rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import ListModelMixin, UpdateModelMixin
from utils.APIResponse import APIResponse
from django.conf import settings
from .models import Banner
from .serializer import BannerSerializer
from django.core.cache import cache


class BannerView(GenericViewSet, ListModelMixin, UpdateModelMixin):
    queryset = Banner.objects.filter(is_delete=False, is_show=True).order_by('orders')[
               :settings.BANNER_COUNT]  # 自定义轮播图片数量
    serializer_class = BannerSerializer

    def list(self, request, *args, **kwargs):
        # 先去 redis 中查询 如果有就返回，如果没有就执行 super() 去数据库中查询
        banner_list = cache.get('banner_list')
        if banner_list:
            print('走了缓存')
            return APIResponse(data=banner_list)
        else:
            print('没走缓存')
            res = super().list(request, *args, **kwargs)
            cache.set('banner_list', res.data)
            return APIResponse(data=res.data)
